#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

pthread_mutex_t mutex;
pthread_cond_t cond;

typedef struct Node{
    int number;
    struct Node *next;
}Node;

Node* head=NULL;

/* 生产者 */
void* producer(void* arg){
    while(1){
        pthread_mutex_lock(&mutex);
        Node* newNode=calloc(1,sizeof(Node));
        newNode->number=rand()%1000;
        newNode->next=head;
        head=newNode;
        printf("生产者 id: %ld , number: %d \n",pthread_self(),newNode->number);
        pthread_mutex_unlock(&mutex);
        pthread_cond_signal(&cond);
        sleep(rand()%3);
    }
    pthread_exit(NULL);
}
/* 消费者 */
void* consumer(void* arg){
    while(1){
        pthread_mutex_lock(&mutex);
        while(head==NULL){
            pthread_cond_wait(&cond,&mutex);
        }
        Node* node=head;
        printf("消费者 id: %ld , number: %d \n",pthread_self(),node->number);
        head=head->next;
        free(node);
        pthread_mutex_unlock(&mutex);
        sleep(rand()%2);
    }
    pthread_exit(NULL);
}
int main()
{
    pthread_mutex_init(&mutex,NULL);
    pthread_cond_init(&cond,NULL);
    
    pthread_t t1[5]={0};
    pthread_t t2[5]={0};
    int length=sizeof(t1)/sizeof(t1[0]);

    for(int i=0;i<length;i++){
        pthread_create(t1+i,NULL,producer,NULL);
        pthread_create(t1+i,NULL,consumer,NULL);
    }
    for(int i=0;i<length;i++){
        pthread_join(t1[i],NULL);
        pthread_join(t2[i],NULL);
    }

    pthread_cond_destroy(&cond);
    pthread_mutex_destroy(&mutex);
    return 1;
}

